package org.example.netty.client;

import cn.hutool.core.util.ObjectUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.example.netty.model.DockerStart;
import org.example.netty.model.DockerStop;
import org.example.netty.model.Header;
import org.example.netty.model.JsonSendMsg;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class FepClient {

    private Integer port;
    private String host;
    private String operation;
    private String devManufacturer;

    public FepClient(int port, String host, String operation, String devManufacturer) {
        this.port = port;
        this.host = host;
        this.operation = operation;
        this.devManufacturer = devManufacturer;
    }

    public static void main(String[] args) {
        FepClient fepClient = new FepClient(Integer.valueOf(args[1]), args[0], args[2], args[3]);
//        System.out.println(new Date());
//        FepClient fepClient = new FepClient(8801,"192.168.2.21", "stop", null);
        fepClient.start();
//        System.out.println(new Date());
    }


    public void start() {
        NioEventLoopGroup group = new NioEventLoopGroup();

        // 创建一个调度程序，10秒后终止程序
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.schedule(() -> {
            System.exit(0);
        }, 10, TimeUnit.SECONDS);

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.option(ChannelOption.TCP_NODELAY, true)
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.wrappedBuffer("<?endn?>".getBytes())));
                            pipeline.addLast(new MessageCodec());
                            pipeline.addLast(new ClientHandler());
                        }
                    });
//            long startTime = System.currentTimeMillis();
            ChannelFuture future = bootstrap.connect(host, port).sync();
//            System.out.println("连接耗时：" + (System.currentTimeMillis() - startTime) + " ms");

            JsonSendMsg json = generateMessage(operation, devManufacturer);
            if (ObjectUtil.isNull(json)) {
                System.exit(0);
            }

//            long sendStart = System.currentTimeMillis();
            future.channel().writeAndFlush(json).addListener((ChannelFutureListener) sendFuture -> {
//                long sendCost = System.currentTimeMillis() - sendStart;
//                System.out.println("发送耗时：" + sendCost + " ms");
//
//                long total = System.currentTimeMillis() - startTime;
//                System.out.println("启动总耗时：" + total + " ms");

                // 不等待响应，发送完成就退出
                System.exit(0);
            });

//            System.out.println("启动总耗时：" + (System.currentTimeMillis() - startTime) + " ms");
        } catch (Exception e) {
        } finally {
            group.shutdownGracefully();
            executorService.shutdown(); // 确保在程序正常结束时，终止调度程序
        }
    }

    public JsonSendMsg generateMessage(String inputStr,String devManufacturer) {
//        log.info("generateMessage input:" + inputStr);
        Header header = new Header();
        JsonSendMsg sendMsg = new JsonSendMsg<>();
        // 构造发送的对象
        if (ObjectUtil.isNotNull(devManufacturer) && (devManufacturer.contains("兆和") || devManufacturer.contains("ZHAOHE"))) {
            switch (inputStr) {
                case "start":
                    header.setFunName("dockerImgStart");
                    header.setTimestamp(String.valueOf(System.currentTimeMillis()));
                    header.setSid("406a7b7f07754ed3a16f51661695dd2a");
                    DockerStart dockerStart = new DockerStart();
                    dockerStart.setDockerConName("ppcgost");
//                dockerStart.setAppStartPara("/bin/ssserver -s 0.0.0.0 -p 8803 -k 'tsgz&$2019' -m aes-256-cfb");
                    dockerStart.setAppStartPara("-L=ss://aes-256-cfb:'tsgz&$2019'@:8803");
                    dockerStart.setDockerImgName("tsgz/gostapp");
                    dockerStart.setStartCommand("");
                    dockerStart.setDockerConIp("8803:8803 --net=host");
                    dockerStart.setDockerConDataVol("");
                    sendMsg.setHeader(header);
                    sendMsg.setData(dockerStart);
                    break;
                case "stop":
                    header.setFunName("dockerImgStop");
                    header.setTimestamp(String.valueOf(System.currentTimeMillis()));
                    header.setSid("3d852a891ae443b7928052426eb045a1");
                    DockerStop dockerStop = new DockerStop();
                    dockerStop.setDockerConName("ppcgost");
                    dockerStop.setStopCommand("-");
                    sendMsg.setHeader(header);
                    sendMsg.setData(dockerStop);
                    break;
                case "exit":
                    System.exit(0);
                default:
                    System.out.println("输入有误请重新输入！");
                    return null;
            }
        } else if (ObjectUtil.isNotNull(devManufacturer) && (devManufacturer.contains("鼎信")|| devManufacturer.contains("DINGXIN"))) {
            switch (inputStr) {
                case "start":
                    header.setFunName("dockerImgStart");
                    header.setTimestamp(String.valueOf(System.currentTimeMillis()));
                    header.setSid("406a7b7f07754ed3a16f51661695dd2a");
                    DockerStart dockerStart = new DockerStart();
                    dockerStart.setDockerConName("ssServer");
                    dockerStart.setAppStartPara("/bin/ssserver -s 0.0.0.0 -p 8803 -k 'tsgz&$2019' -m aes-256-cfb");
                    dockerStart.setDockerConOption("-d");
                    dockerStart.setDockerImgName("tsgz/shadowsocks");
                    dockerStart.setStartCommand("");
                    dockerStart.setDockerConIp("--net=host");
                    dockerStart.setDockerConDataVol("");
                    sendMsg.setHeader(header);
                    sendMsg.setData(dockerStart);
                    break;
                case "stop":
                    header.setFunName("dockerImgStop");
                    header.setTimestamp(String.valueOf(System.currentTimeMillis()));
                    header.setSid("3d852a891ae443b7928052426eb045a1");
                    DockerStop dockerStop = new DockerStop();
                    dockerStop.setDockerConName("ssServer");
                    dockerStop.setStopCommand("-");
                    sendMsg.setHeader(header);
                    sendMsg.setData(dockerStop);
                    break;
                case "exit":
                    System.exit(0);
                default:
                    System.out.println("输入有误请重新输入！");
                    return null;
            }
        } else {
            switch (inputStr) {
                case "start":
                    header.setFunName("dockerImgStart");
                    header.setTimestamp(String.valueOf(System.currentTimeMillis()));
                    header.setSid("406a7b7f07754ed3a16f51661695dd2a");
                    DockerStart dockerStart = new DockerStart();
                    dockerStart.setDockerConName("ssServer");
                    dockerStart.setAppStartPara("/bin/ssserver -s 0.0.0.0 -p 8803 -k 'tsgz&$2019' -m aes-256-cfb");
                    dockerStart.setDockerConOption("-d");
                    dockerStart.setDockerImgName("tsgz/shadowsocks");
                    dockerStart.setStartCommand("");
                    dockerStart.setDockerConIp("8803:8803 --net=host");
                    dockerStart.setDockerConDataVol("");
                    sendMsg.setHeader(header);
                    sendMsg.setData(dockerStart);
                    break;
                case "stop":
                    header.setFunName("dockerImgStop");
                    header.setTimestamp(String.valueOf(System.currentTimeMillis()));
                    header.setSid("3d852a891ae443b7928052426eb045a1");
                    DockerStop dockerStop = new DockerStop();
                    dockerStop.setDockerConName("ssServer");
                    dockerStop.setStopCommand("-");
                    sendMsg.setHeader(header);
                    sendMsg.setData(dockerStop);
                    break;
                case "exit":
                    System.exit(0);
                default:
                    System.out.println("输入有误请重新输入！");
                    return null;
            }
        }

        return sendMsg;
    }
}






